package cn.edt.ctbu.thymeleaf.service.impl;


import cn.edt.ctbu.thymeleaf.constain.REnum;
import cn.edt.ctbu.thymeleaf.domain.Student;
import cn.edt.ctbu.thymeleaf.exception.RException;
import cn.edt.ctbu.thymeleaf.repository.StudentRepository;
import cn.edt.ctbu.thymeleaf.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentImplService implements StudentService {
    @Autowired
    private StudentRepository studentRepository;
    @Override

    //    获取所有学生数据
    public List<Student> findAll(){
        return studentRepository.findAll();
    };

    //分页，带过滤的查询
    public Page<Student> findAll(Example<Student> student, Pageable pageable){
        return studentRepository.findAll(student,pageable);
    }

    //        只支持分页的查询
    public Page<Student> findAll(Pageable pageable){

        return studentRepository.findAll(pageable);
    };


    public Student insert(Student student){

        return studentRepository.save(student);
    }
    public Student update(Student student) {

        return studentRepository.save(student);
    }
    public void delete(Student student) {

        studentRepository.delete(student);
    }

    public void delete(Integer id){
        Student student=new Student();
        student.setId(id);
        studentRepository.delete(student);
    }

    public List<Student> findByName(String name){
        return studentRepository.findByName(name);
    }

    public List<Student> findByNo(String no){
        return studentRepository.findByNo(no);
    }

    public List<Student> findBySex(Integer sex){return studentRepository.findBySex(sex);}

    public Student getById(Integer id){
        Student student=studentRepository.findById(id).orElse(null);
        return student;
    }

    public Student validateUsernameAndPassword(String username,String password) throws Exception{
        List<Student> students=studentRepository.findByNo(username);
        if(students.size()>0){
            Student student=students.get(0);
            if(student.getPassword().equals(password)){
                return student;
            }else {
                throw new RException(REnum.LOGIN_ERR);
            }

        }else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }

    public List<Student> findByNameAndPassword(String name,String password){
        return studentRepository.findByNameAndPassword(name,password);
    }


}
